<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<%@include file="/WEB-INF/base.jspf"%>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>系统红包管理</title>
<style type="text/css">
.wrapper_buttons input {
	height: 32px;
	width: 174px;
	margin-left: 10px;
}

.wrapper_buttons button {
	margin-left: 10px;
}
	.p-c-flexwrapper {
		display:flex;
		align-items:center;
		margin-right:16px;
		margin-bottom:16px;
	}
	.p-c-flexwrapper > span {
		width:80px;
	}
		.modal-dialog {
		max-width: 1000px;
	}
	.p-c-flexwrapper > .form-control {
		width:180px;
	}
				.disButton{color:#F8CDC2;background:#f3a495}
			.actButton{color:yellow;background: #D85940;}
table th,table tr,table td {
text-align: center;
vertical-align:middle;
}
	#setRed .input-group{margin: 20px 0;}
</style>
</head>
<body>
	<div style="display:flex;justify-content:flex-end;">
		<button  class="btn btn-info btn-lg"  id="zdpfhbsz" style="margin-right: 30px;">自动派发红包设置</button>
		<button  class="save btn btn-primary btn-lg"  id="button-i-paifahongbao">派发红包</button>
	</div>
	<table id="table-i-qqAccountList" class="table table-striped table-bordered table-hover" style="margin-top: 20px;">
		<thead>
			<tr>
				<th style="display:none;"></th>
				<th>时间</th>
				<th>红包类型</th>
				<th>红包总金额(元)</th>
				<th>领取状态</th>
				<th>操作</th>
				<th style="display:none;"></th>
				<th style="display:none;"></th>
			</tr>
		</thead>
		<tbody>
		</tbody>
	</table>
	
<div class="modal fade" id="noticeModal" tabindex="-1" role="dialog" aria-labelledby="noticeModal" aria-hidden="true">
    <div class="modal-dialog class-fake-alert">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
            </div>
            <div class="modal-body" ></div>
            <div class="modal-footer">	      
                <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal -->
</div>   	

<div class="modal fade" id="setRed" tabindex="-1" role="dialog" aria-labelledby="" aria-hidden="true">
    <div class="modal-dialog class-fake-alert" style="width: 400px;">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
            	<h4 class="modal-title">自动派发红包设置</h4>
            </div>
            <div class="modal-body" style="text-align:center;" >
            	<button onclick="kaiguan(this)" class="btn btn-success" id="kaiqi" style="width:80%">开启</button>
            	<div class="input-group">
            		<span class="input-group-addon">红包类型</span>
            		<span class="form-control type"  >
            			<input name="type" type="radio" value="固定红包" checked="checked" class="guding"/>固定红包　　
            			<input name="type" type="radio" value="拼手气红包" class="pinshouqi"/>拼手气红包
            		</span>
            	</div>
            	<div class="input-group">
            		<span class="input-group-addon">红包留言</span>
            		<input class="form-control" id="message"  />
            	</div>
            	<div class="input-group">
            		<span class="input-group-addon">红包个数</span>
            		<input class="form-control" id="geshu" type="number"  />
            	</div>
            	<div class="input-group">
            		<span class="input-group-addon">红包金额</span>
            		<input class="form-control" id="jine" type="number" />
            	</div>
            	<div class="input-group">
            		<span class="input-group-addon">时间间隔</span>
            		<input class="form-control" id="time" type="number" />
            	</div>
            </div>
            <div class="modal-footer">	      
                <button id="save" class="btn btn-primary" data-dismiss="modal">确定</button>
                <button class="btn btn-default" data-dismiss="modal">取消</button>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal -->
</div>  

<!-- 发红包 start-->
<div class="modal fade" id="redenvelope" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog" style="top:10%;margin: 0 auto;max-width:420px;">
        <div class="modal-content" style="border-radius:0px;background-color: transparent;">
        <div >
        	<div style="height: 50px;line-height:50px;padding-left: 20px;background: #D85940;">
        		<p style="color:#FFE8B6;font-size: 14px;">发红包</p>
        	</div>
        	 <div class="modal-body" style="background: #F1F1F1;padding: 20px;">
            	<div style="background: white;border-radius: 3px;padding:16px 10px;">
            		<span style="display: inline-block;width: 30%" id="redPack"><span style="color: white;background: orange;padding: 2px">拼</span> 总金额</span>
					<input type="number" style="width: 60%;border:0;text-align: right;" placeholder="0.00" value="" />
            		<span style="display: inline-block;width: 4%">元</span>
            	</div>
            	<p style="padding: 12px 2px;font-size: 12px;" id="changgeRedPack">单个金额随机（最少 0.1），<a style="font-size: 12px;color:blue;">改为普通红包</a></p>
            	<div style="background: white;border-radius: 3px;padding:16px 10px;">
            		<span style="display: inline-block;width: 30%">红包个数</span>
					<input type="number" style="width: 60%;border: 0;text-align: right;" placeholder="填写个数" value="" />
            		<span style="display: inline-block;width: 4%">个</span>
            	</div>
            	<br>
            	<div style="background: white;border-radius: 3px;padding:16px 10px;">
            		<span style="display: inline-block;width: 30%">留言</span>
					<input style="width: 64%;border: 0;text-align: right;" placeholder="恭喜发财，大吉大利" />
            	</div>
            	<br>
            	<button class="sqjhb disButton" style="width: 100%;border: 0;height: 40px;line-height: 40px;border-radius:4px;letter-spacing: 2px; ">塞钱进红包</button>
			</div>
        </div>
        </div>
    </div>
</div>
	
<!-- 模态框（Modal） -->
<div class="modal fade" id="detailLingQu" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                <h4 class="modal-title" id="myModalLabel">领取人列表</h4>
            </div>
            <div class="modal-body">
			 	<table id="lingquTable" class="table table-striped table-bordered table-hover" style="margin-top: 20px;">
					<thead>
						<tr>
							<th>领取人</th>
							<th>领取金额(元)</th>
						</tr>
					</thead>
					<tbody>
					</tbody>
				</table>           	
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div>
<!-- /.modal -->	
	
	<script type="text/javascript" src="/js/zhengzeTools.js"></script>
	<script type="text/javascript">
	
	function kaiqi(){
		$("#kaiqi").addClass("btn-danger")
		$("#kaiqi").removeClass("btn-success")
		$("#kaiqi").text("关闭")
		$("#message").attr("disabled","disabled");
		$("#time").attr("disabled","disabled");
		$("#geshu").attr("disabled","disabled");
		$("#jine").attr("disabled","disabled");
		$(".type").attr("disabled","disabled");
		$("#save").attr("disabled","disabled");
	}
	function guanbi(t){
		$("#kaiqi").addClass("btn-success")
		$("#kaiqi").removeClass("btn-danger")
		$("#kaiqi").text("开启")
		$("#message").removeAttr("disabled");
		$("#time").removeAttr("disabled");
		$("#geshu").removeAttr("disabled");
		$("#jine").removeAttr("disabled");
		$(".type").removeAttr("disabled");
		$("#save").removeAttr("disabled");
	}
	function kaiguan(){
		var num=1;
		if($("#kaiqi").attr("class").indexOf("success")!=-1){
			num=1;
			kaiqi()
		}else{
			num=0;
			guanbi()
		}
		$.ajax({
			type:"post",
			url: "/kajhsgweasdqtwehghasfdnsak6868/updateChatRedPackageState.do",
			dataType:"json",
			data:{"num":num},
			success:function(data){
			}
		})
	}
	$("#zdpfhbsz").click(function(){
		$.ajax({
			type:"post",
			url: "/kajhsgweasdqtwehghasfdnsak6868/findSystemRedPackgeSetup.do",
			dataType:"json",
			success:function(data){
				var d=data.data;
				if(d.typeofredenvelopes=="拼手气红包"){
					$(".pinshouqi").attr("checked","checked");
					$(".guding").removeAttr("checked")
				}else{
					$(".guding").attr("checked","checked");
					$(".pinshouqi").removeAttr("checked")
				}
				$("#message").val(d.leavingamessage);
				$("#time").val(Number(d.time)/1000);
				$("#geshu").val(d.numberofredpackets);
				$("#jine").val(d.redenvelopes);
				
				$.ajax({
					type:"post",
					url: "/kajhsgweasdqtwehghasfdnsak6868/findChatRedPackageSwitch.do",
					dataType:"json",
					success:function(data){
						if(data.data==1){
							kaiqi()
						}else{
							guanbi();
						}
					}
				})
			}
		})
		$("#setRed").modal("show")
	})
	$("#save").click(function(){
		var type=$("input[name='type']:checked").val();
		var message=$("#message").val();
		var geshu =$("#geshu").val();
		var jine=$("#jine").val();
		var time=$("#time").val();
		$.ajax({
			type:"post",
			url: "/kajhsgweasdqtwehghasfdnsak6868/updateSystemRedPackageSetup.do",
			dataType:"json",
			data:{ "redenvelopes": jine,"numberofredpackets":geshu,"leavingamessage":message,"typeofredenvelopes":type,"time":Number(time)*1000},
			success:function(data){
			}
		})	
	})
	var websocket = null;
	var url=window.location.href.replace("kajhsgweasdqtwehghasfdnsak6868/systemRedPackage.do","all").replace("http","ws")
	//判断当前浏览器是否支持WebSocket
	if ('WebSocket' in window) {
		websocket = new WebSocket(url+"?name=0");
	} else {
		showNoticeModal("不支持聊天系统")
	};
	$("#button-i-paifahongbao").on("click", function(e) {
		$("#redenvelope").modal("show")
	})
	//连接发生错误的回调方法
	websocket.onerror = function() {
		showNoticeModal("error");
	};

	//连接成功建立的回调方法
	 websocket.onopen = function(event){
	};

	//接收到消息的回调方法
	websocket.onmessage = function(event) {
	};

	//连接关闭的回调方法
	websocket.onclose = function() {
		showNoticeModal("与系统聊天室断开连接")
	};

	//监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
	window.onbeforeunload = function() {
		websocket.close();
	};		
	
	
	$("#lingquTable").DataTable({
	      // "bPaginate": true,
	      "bLengthChange": true,      
	      "bSort": false,
	      // "bInfo": true,
	      "bAutoWidth": false,
//		         "bServerSide":true,
	      'aLengthMenu':[10, 20],
	       "searching": false,
	       "dom": `ftp`,
//		    "searching": true,l
	       "language": {//语言设置  
	            "lengthMenu": "每页显示 _MENU_ 条记录",     
	            "zeroRecords": "没有检索到数据",     
	            "sInfo": "当前显示 _START_ 到 _END_ 条，共 _TOTAL_ 条记录",     
	            "info": "没有数据",     
	            "oPaginate": {     
	                "sFirst": "首页",     
	                "sPrevious": "前一页",     
	                "sNext": "后一页",     
	                "sLast": "尾页"    
	          	},
	            "search":"搜索:",
	            "infoFiltered":   "(从  _MAX_ 记录中搜索出结果)",
	            "infoEmpty":      "没有找到匹配的信息",
	         },
	         "destroy": true,
   		 })			
	
		$("#table-i-qqAccountList").DataTable({
	      // "bPaginate": true,
	      "bLengthChange": true,      
	      "bSort": false,
	      // "bInfo": true,
	      "bAutoWidth": false,
//		         "bServerSide":true,
	      'aLengthMenu':[10, 20],
	       "searching": false,
	       "dom": `ftp`,
//		    "searching": true,l
	       "language": {//语言设置  
	            "lengthMenu": "每页显示 _MENU_ 条记录",     
	            "zeroRecords": "没有检索到数据",     
	            "sInfo": "当前显示 _START_ 到 _END_ 条，共 _TOTAL_ 条记录",     
	            "info": "没有数据",     
	            "oPaginate": {     
	                "sFirst": "首页",     
	                "sPrevious": "前一页",     
	                "sNext": "后一页",     
	                "sLast": "尾页"    
	          	},
	            "search":"搜索:",
	            "infoFiltered":   "(从  _MAX_ 记录中搜索出结果)",
	            "infoEmpty":      "没有找到匹配的信息",
	         },
	         "ajax": {
	        	 "type": "POST",
	        	 "url": "/kajhsgweasdqtwehghasfdnsak6868/findSystemRedPackage.do",
	        	 "dataSrc": function(json) {
	        		 var newData = json.data
	        		 for (var i = 0; i < newData.length; i++) {
	        			 var item = newData[i]
	        			 if (item.type === "固定红包") {
	        				 item.jine = Number(item.jine) * Number(item.count)
	        			 }
	        			 var lingquArr = item.lingqu.replace("0,", "")
	        			 var num = 0
	        			 if (lingquArr !== "") {
		        			 lingquArr = lingquArr.slice(0, lingquArr.length - 1)
		        			 num = lingquArr.split(",").length 				 
	        			 }
	        			 item.lingquzhuangtai = num + "/" + String(item.redpack.split(",").length)
	        		 }
	        		 return newData
	        	 }
	         },
	         "columns": [
						 {"data": "id", "className": "hidden-td id-edit-td"},
						 {"data": "creattime", "className": "creattime-edit-td"},
	                     {"data": "type", "className": "type-edit-td"},
	                     {"data": "jine", "className": "jine-edit-td"},
	                     {"data": "lingquzhuangtai", "className": "lingquzhuangtai-edit-td"},
	                     {"data": null, "defaultContent": "<button class='btn btn-info btn-c-editBankInfo btn-sm'>详情</button>"},
	                     {"data": "lingqu", "className": "hidden-td lingqu-edit-td"},
	                     {"data": "redpack", "className": "hidden-td redpack-edit-td"},
                     ]        
	   		 })		

 $("#redenvelope button").on("click",function(){
		if($(this).attr("class").indexOf("disButton")==-1){
			var a=$("#redenvelope input").eq(2).val()||"恭喜发财，大吉大利";
			var message = "0" + "k45jk459fgjdf986kjh98fgdkj3i45y89fdh4598hp90uallk45jk459fgjdf986kjh98fgdkj3i45y89fdh4598hp90u"
				+ $("#redenvelope input").eq(0).val()+"BeanRedPackageJa" + $("#redenvelope input").eq(1).val()+"BeanRedPackageJa"
				+ a +"BeanRedPackageJa" + $("#redenvelope a").text()
			websocket.send(message);
			$("#redenvelope").modal("hide")
			$(".sqjhb").addClass("disButton").removeClass("actButton");
			$("#redenvelope input").val("")
			showNoticeModal("派发成功！")
			setTimeout(function(){$("#table-i-qqAccountList").DataTable().ajax.reload();},1000)
		}
	})	 
	   	
$("#table-i-qqAccountList").on("click", ".btn-c-editBankInfo", function(e) {
	var $tr = $(e.currentTarget).closest("tr")
	var lingquString = $tr.find(".lingqu-edit-td").text().replace("0,", "")
	if (lingquString === "") {
		showNoticeModal("该红包暂无用户领取")
		return
	}
	lingquString = lingquString.slice(0, lingquString.length - 1) 
	var lingquArr = lingquString.split(",")
	var jieArr = $tr.find(".redpack-edit-td").text().split(",")
	$.ajax({
		type:"post",
		url: "/kajhsgweasdqtwehghasfdnsak6868/findUserRedPackageDetails.do",
		dataType:"json",
		data:{ "str": lingquString},
		success:function(data){
			var newData = []
			for (var i = 0; i < lingquArr.length; i++) {
				var newObj = {}
				for (var j = 0; j < data.data.length; j++) {
					if (Number(lingquArr[i]) === Number(data.data[j].id)) {
						newObj.name = data.data[j].name
						break
					}
				}
				newObj.jine = Number(jieArr[i]) / 10;
			}
			newData.push(newObj);
			$("#lingquTable").DataTable({
			      // "bPaginate": true,
			      "bLengthChange": true,      
			      "bSort": false,
			      // "bInfo": true,
			      "bAutoWidth": false,
//				         "bServerSide":true,
			      'aLengthMenu':[10, 20],
			       "searching": false,
			       "dom": `ftp`,
			       "data": newData,
//				    "searching": true,l
			       "language": {//语言设置  
			            "lengthMenu": "每页显示 _MENU_ 条记录",     
			            "zeroRecords": "没有检索到数据",     
			            "sInfo": "当前显示 _START_ 到 _END_ 条，共 _TOTAL_ 条记录",     
			            "info": "没有数据",     
			            "oPaginate": {     
			                "sFirst": "首页",     
			                "sPrevious": "前一页",     
			                "sNext": "后一页",     
			                "sLast": "尾页"    
			          	},
			            "search":"搜索:",
			            "infoFiltered":   "(从  _MAX_ 记录中搜索出结果)",
			            "infoEmpty":      "没有找到匹配的信息",
			         },
			         "destroy": true,
			         "columns": [
		                     { "data": "name" },
		                     { "data": "jine" },
		                 ]			         
		   		 })	
		   	$("#detailLingQu").modal("show")	 
		},
		error: function(e) {
			showNoticeModal("网络繁忙")
		}
	})	
	//
})	
	
	
	// 切换红包
	$("#changgeRedPack").on("click",function(){
		$("#redenvelope input").eq(0).val("");
		$("#redenvelope input").eq(1).val("");
		$(".sqjhb").addClass("disButton").removeClass("actButton");
		if($(this).text().indexOf("固定")!=-1){
			$(this).html("单个金额随机（最少 0.1），<a style='font-size: 12px;color:blue;'>改为普通红包</a>");
			$("#redPack").html("<span style='color: white;background: orange;padding: 2px'>拼</span> 总金额");
		}else{
			$(this).html("每人收到固定金额，<a style='font-size: 12px;color:blue;'>改为拼手气红包</a>");
			$("#redPack").html("单个金额");
		}
	});	
	
	// 输入监听事件
	$("#redenvelope input").on("input",function(){
		var type=$("#redenvelope a").eq(0).text();
		var jine=$("#redenvelope input").eq(0).val().trim();
		var geshu=$("#redenvelope input").eq(1).val().trim();
		var isdy0=(Number(jine)/Number(geshu))>=0.1;
		
		var t=/^[0-9]+$/;
		
		if((geshu!="" && Number(geshu) > 0)&&(jine!="")&&jine>0&&Number(jine) <= 200000&&t.test(geshu)){
			if(type.indexOf("改为普通")!=-1){
				if(isdy0){
					$(".sqjhb").addClass("actButton").removeClass("disButton");
				}else{
					$(".sqjhb").addClass("disButton").removeClass("actButton");
				}
			}else{
				$(".sqjhb").addClass("actButton").removeClass("disButton");
			}
		}else{
			$(".sqjhb").addClass("disButton").removeClass("actButton");
		}
	})	
	
	</script>
</body>
</html>